package com.hu.zhcc.shiro.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hu.zhcc.shiro.dao.CheckGroupDAO;
import com.hu.zhcc.shiro.dao.SetmealDAO;
import com.hu.zhcc.shiro.entity.bo.CheckGroup;
import com.hu.zhcc.shiro.entity.bo.Setmeal;
import com.hu.zhcc.shiro.entity.vo.SetmealVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("setmealService")
@Transactional
public class SetmealServiceImpl implements SetmealService{

    @Autowired
    private SetmealDAO setmealDAO;

    @Override
    public int edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //修改检查组基本信息，操作检查组t_checkgroup表
        int edit = setmealDAO.edit(setmeal);
        if(edit>0) {
            //清理当前检查组关联的检查项，操作中间关系表t_checkgroup_checkitem表
            setmealDAO.deleteAssocication(setmeal.getId());
            //重新建立当前检查组和检查项的关联关系
            Integer checkGroupId = setmeal.getId();
            this.setSetmealAndCheckgroup(checkGroupId, checkgroupIds);
        }
        return edit;
    }

    @Override
    public int add(Setmeal setmeal, Integer[] checkgroupIds) {
        int add = setmealDAO.add(setmeal);
        if (add>0) {
            //设置检查组和检查项的多对多的关联关系，操作t_checkgroup_checkitem表
            Integer setmealId = setmeal.getId();
            this.setSetmealAndCheckgroup(setmealId,checkgroupIds);
        }
        return add;
    }

    @Override
    public void setSetmealAndCheckGroup(Map map) {

    }

    @Override
    public PageInfo<Setmeal> findByCondition(SetmealVO setmealVO) {
        PageHelper.startPage(setmealVO.getPageNum(),setmealVO.getPageSize());
        List<Setmeal> byCondition = setmealDAO.findByCondition(setmealVO.getQueryString());
        PageInfo<Setmeal> setmealPageInfo = new PageInfo<>(byCondition);
        return setmealPageInfo;
    }

    @Override
    public int delete(Integer id) {
        setmealDAO.deleteAssocication(id);
        int delete = setmealDAO.delete(id);
        return delete;
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDAO.findByCondition(null);
    }

    @Override
    public Setmeal selectByPrimaryKey(Integer id) {
        return setmealDAO.selectByPrimaryKey(id);
    }

    //设置套餐和检查组多对多关系，操作t_setmeal_checkgroup
    public void setSetmealAndCheckgroup(Integer setmealId,Integer[] checkgroupIds) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkgroupId);
                setmealDAO.setSetmealAndCheckGroup(map);
            }
        }
    }
}
